package cn.bellychang.websocket;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.StreamGobbler;
import org.springframework.stereotype.Component;

import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author ChangLiang
 * @date 2020/3/6
 */
@ServerEndpoint("/tail-log-1")
@Component
public class TailLogEndpoint {

    private Connection connection;

    @OnOpen
    public void onOpen(Session session) {
        try {
            if (login()) {
                ch.ethz.ssh2.Session sshSession = connection.openSession();
                sshSession.execCommand("tail -0f /var/log/prometheus.log");
                InputStream inputStream = new StreamGobbler(sshSession.getStdout());

                // 一定要启动新的线程，防止InputStream阻塞处理WebSocket的线程
                TailLogThread thread = new TailLogThread(inputStream, session);
                thread.setName("tail log thread");
                thread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean login() throws IOException {
        connection = new Connection("192.168.211.101");
        connection.connect();
        return connection.authenticateWithPassword("root", "1230456");
    }
}
